﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.IO;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;

namespace EcoSystem
{
    public class NewtownsoftBinder : IModelBinder
    {
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }
            if (bindingContext.HttpContext.Request.Method == "POST" ||
                bindingContext.HttpContext.Request.Method == "PUT")
            {
                StreamReader stream = new StreamReader(bindingContext.HttpContext.Request.Body);
                string body = await stream.ReadToEndAsync();
                var model = JsonConvert.DeserializeObject(body, bindingContext.ModelType);
                model.ConvertJObjectDictonary();
                bindingContext.Result = ModelBindingResult.Success(model);
            }
            await Task.CompletedTask;
        }
    }

    [AttributeUsage(
      AttributeTargets.Parameter |
      AttributeTargets.Property |
      AttributeTargets.Class |
      AttributeTargets.Enum |
      AttributeTargets.Struct,
      AllowMultiple = false,
      Inherited = true)]
    public class JsonBinderAttribute : ModelBinderAttribute
    {
        public JsonBinderAttribute() : base(typeof(NewtownsoftBinder))
        {

        }
    }
}
